package cn.wolfcode.cloud.shop.mq;

import cn.wolfcode.cloud.shop.consts.MQConstants;
import cn.wolfcode.cloud.shop.resp.Result;
import cn.wolfcode.cloud.shop.util.JSONUtil;
import cn.wolfcode.cloud.shop.ws.WebSocketServer;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;

/**
 * @author Administrator
 */
@Component
@RocketMQMessageListener(
    topic = MQConstants.SECKILL_ORDER_TOPIC,
    consumerGroup = MQConstants.SECKILL_ORDER_SUCCESS_CONSUMER_GROUP,
    selectorExpression = MQConstants.SECKILL_ORDER_SUCCESS_TAG
)
public class SeckillOrderSuccessMQListener implements RocketMQListener<Result> {

    private Logger logger = LoggerFactory.getLogger("SECKILL_ORDER_SUCCESS_MQ_LISTENER");


    @Override
    public void onMessage(Result message) {
        Map<String,Object> data = (Map<String, Object>) message.getData();
        String msgJSON = JSONUtil.toJsonString(message);
        logger.info("收到订单创建的结果:{}"+msgJSON);

        String uuid = (String) data.get("uuid");
        Session session = WebSocketServer.clients.get(uuid);
        if(session != null){
            try {
                session.getBasicRemote().sendText(msgJSON);
            } catch (IOException e) {
                logger.error("消息发送异常:",e);
            }
        }
    }
}
